package org.example.Handler;

import org.example.Command.FileMessage;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.example.Constant.clientDirectory;

public interface SaveFile {
    static void saveFile(FileMessage msg, File rootPath) throws IOException {
        if (msg.getFlag() == -1) {
            byte[] bytes = msg.getBytes();
            String path;
            if (msg.getFilePath() == null) {
                path = rootPath + File.separator + msg.getFile_md5();
            } else {
                path = rootPath + File.separator + msg.getFilePath();
            }

            File file = new File(path);
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek(msg.getStarPos());
            int i = msg.getEndPos() - msg.getStarPos();
            randomAccessFile.write(bytes, 0, i);
            if (i < 1024) {
                System.out.println("文件保存" + file);
            }
        } else {
            //创建目录
            Path path = Paths.get(clientDirectory + File.separator + msg.getFilePath());
            if (!Files.exists(path)) {
                Files.createDirectory(path);
            }
        }
    }
}
